package com.wcar.sso.config;

import com.wcar.sso.realm.MyRealm;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.DelegatingFilterProxy;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    @Bean(name = "mySecurityManager")
    public DefaultWebSecurityManager securityManager(){
        DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
        //设置securityManager得realm对象
        securityManager.setRealm(myRealm());
        return securityManager;
    }
    @Bean
    public MyRealm myRealm(){
        MyRealm myRealm=new MyRealm();
        //设置加密器
        myRealm.setCredentialsMatcher(credentialsMatcher());
        return myRealm;
    }
    @Bean
    public CredentialsMatcher credentialsMatcher(){
        HashedCredentialsMatcher credentialsMatcher=new HashedCredentialsMatcher();
        credentialsMatcher.setHashIterations(5);
        credentialsMatcher.setHashAlgorithmName("MD5");
        return credentialsMatcher;
    }

    @Bean(name = "shiroFilter")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(){
        ShiroFilterFactoryBean filterFactoryBean=new ShiroFilterFactoryBean();
        filterFactoryBean.setSecurityManager(securityManager());
        //未登录跳转的路径
        filterFactoryBean.setLoginUrl("/unlogin");
        //设置过滤规则
        Map<String,String> map=new HashMap<>();
        map.put("/sso/login","anon");
        map.put("/**","anon");
        filterFactoryBean.setFilterChainDefinitionMap(map);
        return filterFactoryBean;
    }
    //注册shiro过滤器
    @Bean
    public FilterRegistrationBean<Filter> registrationBean(){
        FilterRegistrationBean<Filter> registrationBean=new FilterRegistrationBean<>();
        registrationBean.setName("shiroFilter");
        registrationBean.setFilter(new DelegatingFilterProxy());
        registrationBean.addUrlPatterns("/*");
        return registrationBean;
    }
}